package com.epam.ws.anatomist.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.epam.ws.anatomist.common.exception.ErrorMessages;
import com.epam.ws.anatomist.common.exception.ResourceProcessingException;

public class WsAnatomistUtil
{

	private static final Logger LOGGER = Logger.getLogger(WsAnatomistUtil.class);

	public static InputStream getResourceAsStream(String resourcePath)
	{
		InputStream sourceInputStream = null;
		final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		if (classLoader == null)
		{
			LOGGER.error(ErrorMessages.CLASSLOADER_GETTING_ERROR);
			throw new ResourceProcessingException(ErrorMessages.CLASSLOADER_GETTING_ERROR);
		}
		sourceInputStream = classLoader.getResourceAsStream(resourcePath);
		if (sourceInputStream == null)
		{
			LOGGER.error(ErrorMessages.INPUT_STREAM_GETTING_ERROR);
			throw new ResourceProcessingException(ErrorMessages.INPUT_STREAM_GETTING_ERROR);
		}
		return sourceInputStream;
	}

	public static <T> String getPackageName(Class<T> pojoClass)
	{
		if (pojoClass != null)
		{
			Package pojoPackage = pojoClass.getPackage();
			if (pojoPackage != null)
			{
				return pojoPackage.getName();
			}
			LOGGER.warn(String.format(ErrorMessages.PACKAGE_NAME_RETRIEVE_WARN, pojoClass.getName()));
			return "";
		}
		else
		{
			return null;
		}
	}

	public static String readFileToString(String filePath)
	{
		InputStream fileInputStream = getResourceAsStream(filePath);
		if (fileInputStream == null)
		{
			return null;
		}
		Writer writer = new StringWriter();
		char[] buffer = new char[1024];
		try
		{
			Reader reader = new BufferedReader(new InputStreamReader(fileInputStream));
			int n;
			while ((n = reader.read(buffer)) != -1)
			{
				writer.write(buffer, 0, n);
			}
		}
		catch (IOException e)
		{
			LOGGER.warn("Error during reading file to String");
			return null;
		}
		finally
		{
			try
			{
				fileInputStream.close();
			}
			catch (IOException e)
			{
				LOGGER.warn("File input strean is not closed");
			}
		}
		return writer.toString();
	}

	public static synchronized Properties loadProperties(String propertiesPath)
	{
		Properties properties = new Properties();
		try
		{
			properties.load(WsAnatomistUtil.getResourceAsStream(propertiesPath));
		}
		catch (IOException e)
		{
			LOGGER.warn("Properties are not loaded from location: " + propertiesPath);
			return properties;
		}
		return properties;
	}

}
